from typing import Dict
import numpy as np
from datetime import datetime

class CircuitBreaker:
    """实时熔断机制引擎"""
    
    def __init__(self):
        self.rules = {
            'max_drawdown': 0.1,  # 单日最大回撤10%
            'position_limit': 0.3,  # 单品种持仓限额30%
            'velocity_limit': {    # 交易频率限制
                'window': '5min',
                'count': 50
            }
        }
        self.last_trigger = {}
        
    def validate(self, positions: Dict) -> bool:
        """实时风险检查"""
        checks = [
            self._check_drawdown(positions),
            self._check_position_concentration(positions),
            self._check_trading_velocity()
        ]
        return all(checks)
    
    def _check_drawdown(self, positions):
        """回撤检查"""
        current = positions['current_value']
        peak = positions['peak_value']
        drawdown = (peak - current) / peak
        return drawdown < self.rules['max_drawdown']
    
    def _check_position_concentration(self, positions):
        """持仓集中度检查"""
        total = sum(positions.values())
        return all(v/total < self.rules['position_limit'] for v in positions.values())
    
    def _check_trading_velocity(self):
        """交易频率检查"""
        now = datetime.now()
        if 'last_check' not in self.last_trigger:
            self.last_trigger['last_check'] = now
            self.last_trigger['count'] = 0
            return True
            
        if (now - self.last_trigger['last_check']).seconds < 300:  # 5分钟窗口
            self.last_trigger['count'] += 1
            return self.last_trigger['count'] < self.rules['velocity_limit']['count']
        else:
            self.last_trigger = {'last_check': now, 'count': 0}
            return True

